package com.yss.ams.demo.controller;

import com.yss.ams.demo.pojo.User;
import com.yss.ams.demo.service.DataSourceTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author shenyao
 * @date 2021/3/28
 * @description:
 */

@RestController
public class TestController {
    @Autowired
    DataSourceTestService dataSourceTestServiceImpl;

    @RequestMapping("/testInsertOne")
    @Transactional
    public String testInsertOne() {
        User user = new User();
        user.setUsername("testUserOne");
        user.setAge(10);
        try {
            dataSourceTestServiceImpl.testInsertUser(user);
        } catch (Exception e) {
            System.out.println("触发事务回滚");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return  "OK";
    }

    @RequestMapping("/testUserTwo")
    @Transactional
    public String testUserTwo() {
        User user = new User();
        user.setUsername("testUserTwo");
        user.setAge(10);
        try {
            dataSourceTestServiceImpl.testInsertUser2(user);
            int num = 10/0;
        } catch (Exception e) {
            System.out.println("触发事务回滚" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return  "OK";
    }

    @RequestMapping("/testUserTwo2")
    @Transactional
    public String testUserTwo2() {
        User user = new User();
        user.setUsername("testUserTwo2");
        user.setAge(10);
        dataSourceTestServiceImpl.testInsertUser2(user);
        int num = 10/0;
        return  "OK";
    }

    @RequestMapping("/testInsert")
    @Transactional
    public String testInsert() {
        User user = new User();
        user.setUsername("testInsert");
        user.setAge(10);
        dataSourceTestServiceImpl.testInsertUser(user);
        dataSourceTestServiceImpl.testInsertUser2(user);
        return  "OK";
    }

    @RequestMapping("/testInsert2")
    @Transactional
    public String testInsert2() {
        User user = new User();
        user.setUsername("testInsert2");
        user.setAge(10);
        dataSourceTestServiceImpl.testInsertUser(user);
        dataSourceTestServiceImpl.testInsertUser2(user);
        int num = 10/0;
        return  "OK";
    }

}
